let currentAlgorithm = 'md5';

// 初始化
window.addEventListener('load', function() {
    const input = document.getElementById('hash-input');
    
    if (!input) {
        console.error('找不到输入元素');
        return;
    }
    
    // 监听输入变化
    input.oninput = function() {
        // 根据当前算法调用相应的更新函数
        if (currentAlgorithm === 'hmac') {
            if (typeof updateHMAC === 'function') {
                updateHMAC();
            }
        } else {
            updateHash();
        }
    };
    
    // 初始显示空结果
    updateHash();
});

function switchAlgorithm(algorithm) {
    currentAlgorithm = algorithm;
    
    // 更新标签页状态
    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    // 隐藏所有配置面板
    const algorithmSelectContainer = document.getElementById('algorithm-select-container');
    const paramsDiv = document.getElementById('crypto-params');
    const hmacConfig = document.getElementById('hmac-config');
    
    algorithmSelectContainer.style.display = 'none';
    paramsDiv.style.display = 'none';
    if (hmacConfig) {
        hmacConfig.style.display = 'none';
    }
    
    // 根据算法显示对应配置
    if (algorithm === 'sha') {
        algorithmSelectContainer.style.display = 'block';
        updateHash();
    } else if (algorithm === 'aes' || algorithm === 'des') {
        paramsDiv.style.display = 'block';
    } else if (algorithm === 'hmac') {
        if (hmacConfig) {
            hmacConfig.style.display = 'block';
        }
        // 调用 updateHMAC 函数（如果存在）
        if (typeof updateHMAC === 'function') {
            updateHMAC();
        }
    } else {
        updateHash();
    }
}

function updateHash() {
    const input = document.getElementById('hash-input').value;
    
    if (!input) {
        document.getElementById('results').innerHTML = '<p style="text-align: center; color: #95a5a6;">请输入文本进行处理</p>';
        return;
    }
    
    let results = [];
    
    switch (currentAlgorithm) {
        case 'md5':
            results = getMD5Results(input);
            break;
        case 'sha':
            results = getSHAResults(input);
            break;
        case 'base64':
            results = getBase64Results(input);
            break;
        default:
            results = [];
    }
    
    displayResults(results);
}

function getMD5Results(input) {
    const encoding = document.getElementById('encoding-select').value;
    const transform = document.getElementById('transform-select').value;
    
    const hash = CryptoJS.MD5(input);
    
    let result32, result16;
    if (encoding === 'base64') {
        result32 = hash.toString(CryptoJS.enc.Base64);
        result16 = result32; // Base64 没有16位概念
    } else {
        const hexStr = hash.toString();
        result32 = hexStr;
        result16 = hexStr.substring(8, 24);
    }
    
    if (transform === 'upper') {
        result32 = result32.toUpperCase();
        result16 = result16.toUpperCase();
    }
    
    const results = [
        { label: '32位', value: result32 }
    ];
    
    if (encoding === 'hex') {
        results.push({ label: '16位', value: result16 });
    }
    
    return results;
}

function getSHAResults(input) {
    const algorithm = document.getElementById('algorithm-select').value;
    const encoding = document.getElementById('encoding-select').value;
    const transform = document.getElementById('transform-select').value;
    
    let hash;
    switch (algorithm) {
        case 'SHA-1':
            hash = CryptoJS.SHA1(input);
            break;
        case 'SHA-224':
            hash = CryptoJS.SHA224(input);
            break;
        case 'SHA-256':
            hash = CryptoJS.SHA256(input);
            break;
        case 'SHA-384':
            hash = CryptoJS.SHA384(input);
            break;
        case 'SHA-512':
            hash = CryptoJS.SHA512(input);
            break;
        case 'SHA3-224':
            hash = CryptoJS.SHA3(input, { outputLength: 224 });
            break;
        case 'SHA3-256':
            hash = CryptoJS.SHA3(input, { outputLength: 256 });
            break;
        case 'SHA3-384':
            hash = CryptoJS.SHA3(input, { outputLength: 384 });
            break;
        case 'SHA3-512':
            hash = CryptoJS.SHA3(input, { outputLength: 512 });
            break;
        default:
            hash = CryptoJS.SHA256(input);
    }
    
    let result;
    if (encoding === 'base64') {
        result = hash.toString(CryptoJS.enc.Base64);
    } else {
        result = hash.toString();
    }
    
    if (transform === 'upper') {
        result = result.toUpperCase();
    }
    
    return [
        { label: algorithm, value: result }
    ];
}

function getBase64Results(input) {
    const encoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(input));
    let decoded = '';
    try {
        decoded = CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(input));
    } catch (e) {
        decoded = '无法解码（输入不是有效的 Base64）';
    }
    
    return [
        { label: 'Base64 编码', value: encoded },
        { label: 'Base64 解码', value: decoded }
    ];
}

function encryptText() {
    const input = document.getElementById('hash-input').value;
    const key = document.getElementById('crypto-key').value;
    const iv = document.getElementById('crypto-iv').value;
    const mode = document.getElementById('crypto-mode').value;
    const padding = document.getElementById('crypto-padding').value;
    const outputFormat = document.getElementById('crypto-output').value;
    
    if (!input) {
        alert('请输入要加密的文本');
        return;
    }
    
    if (!key) {
        alert('请输入密钥');
        return;
    }
    
    try {
        const keyHash = CryptoJS.enc.Utf8.parse(key);
        const ivHash = iv ? CryptoJS.enc.Utf8.parse(iv) : CryptoJS.enc.Utf8.parse(key);
        
        // 获取加密模式
        const modeObj = CryptoJS.mode[mode];
        
        // 获取填充方式
        const paddingObj = CryptoJS.pad[padding];
        
        const config = {
            mode: modeObj,
            padding: paddingObj
        };
        
        // ECB 模式不需要 IV
        if (mode !== 'ECB') {
            config.iv = ivHash;
        }
        
        let encrypted;
        if (currentAlgorithm === 'aes') {
            encrypted = CryptoJS.AES.encrypt(input, keyHash, config);
        } else if (currentAlgorithm === 'des') {
            encrypted = CryptoJS.DES.encrypt(input, keyHash, config);
        }
        
        // 根据输出格式转换
        let result;
        if (outputFormat === 'Hex') {
            result = encrypted.ciphertext.toString();
        } else {
            result = encrypted.toString();
        }
        
        displayResults([
            { label: '加密结果', value: result }
        ]);
    } catch (err) {
        alert('加密失败: ' + err.message);
    }
}

function decryptText() {
    const input = document.getElementById('hash-input').value;
    const key = document.getElementById('crypto-key').value;
    const iv = document.getElementById('crypto-iv').value;
    const mode = document.getElementById('crypto-mode').value;
    const padding = document.getElementById('crypto-padding').value;
    const outputFormat = document.getElementById('crypto-output').value;
    
    if (!input) {
        alert('请输入要解密的文本');
        return;
    }
    
    if (!key) {
        alert('请输入密钥');
        return;
    }
    
    try {
        const keyHash = CryptoJS.enc.Utf8.parse(key);
        const ivHash = iv ? CryptoJS.enc.Utf8.parse(iv) : CryptoJS.enc.Utf8.parse(key);
        
        // 获取加密模式
        const modeObj = CryptoJS.mode[mode];
        
        // 获取填充方式
        const paddingObj = CryptoJS.pad[padding];
        
        const config = {
            mode: modeObj,
            padding: paddingObj
        };
        
        // ECB 模式不需要 IV
        if (mode !== 'ECB') {
            config.iv = ivHash;
        }
        
        let decrypted;
        
        // 根据输入格式处理
        if (outputFormat === 'Hex') {
            // Hex 格式需要特殊处理
            const cipherParams = CryptoJS.lib.CipherParams.create({
                ciphertext: CryptoJS.enc.Hex.parse(input)
            });
            
            if (currentAlgorithm === 'aes') {
                decrypted = CryptoJS.AES.decrypt(cipherParams, keyHash, config);
            } else if (currentAlgorithm === 'des') {
                decrypted = CryptoJS.DES.decrypt(cipherParams, keyHash, config);
            }
        } else {
            // Base64 格式
            if (currentAlgorithm === 'aes') {
                decrypted = CryptoJS.AES.decrypt(input, keyHash, config);
            } else if (currentAlgorithm === 'des') {
                decrypted = CryptoJS.DES.decrypt(input, keyHash, config);
            }
        }
        
        const result = decrypted.toString(CryptoJS.enc.Utf8);
        
        if (!result) {
            throw new Error('解密失败，请检查密钥、模式、填充方式和密文是否正确');
        }
        
        displayResults([
            { label: '解密结果', value: result }
        ]);
    } catch (err) {
        alert('解密失败: ' + err.message);
    }
}

function displayResults(results) {
    const resultsContainer = document.getElementById('results');
    resultsContainer.innerHTML = results.map((item, index) => `
        <div class="result-item">
            <div class="result-label">${escapeHtml(item.label)}</div>
            <div class="result-value">${escapeHtml(item.value)}</div>
            <button class="copy-btn" data-index="${index}">
                📋
            </button>
        </div>
    `).join('');
    
    // 为每个复制按钮添加事件监听器
    const copyButtons = resultsContainer.querySelectorAll('.copy-btn');
    copyButtons.forEach((button, index) => {
        button.addEventListener('click', () => copyResult(results[index].value, button));
    });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

async function copyResult(text, button) {
    try {
        await navigator.clipboard.writeText(text);
        button.textContent = '✓';
        button.classList.add('copied');
        setTimeout(() => {
            button.textContent = '📋';
            button.classList.remove('copied');
        }, 1500);
    } catch (err) {
        console.error('复制失败:', err);
        // 显示错误提示
        button.textContent = '✗';
        button.style.color = '#e74c3c';
        setTimeout(() => {
            button.textContent = '📋';
            button.style.color = '';
        }, 1500);
    }
}

function updateHMAC() {
    const message = document.getElementById('hash-input').value;
    const keyInput = document.getElementById('hmac-key');
    
    // 检查密钥输入框是否存在
    if (!keyInput) {
        console.error('找不到 HMAC 密钥输入框');
        return;
    }
    
    const key = keyInput.value;
    
    // 输入验证 - 如果消息或密钥为空，显示友好提示
    if (!message || !key) {
        let hint = '';
        if (!message && !key) {
            hint = '请输入消息和密钥';
        } else if (!message) {
            hint = '请输入消息';
        } else {
            hint = '请输入密钥';
        }
        document.getElementById('results').innerHTML = 
            `<p style="text-align: center; color: #95a5a6;">${hint}</p>`;
        return;
    }
    
    const algorithmSelect = document.getElementById('hmac-algorithm');
    const encodingSelect = document.getElementById('hmac-encoding');
    const transformSelect = document.getElementById('hmac-transform');
    
    // 检查配置元素是否存在
    if (!algorithmSelect || !encodingSelect || !transformSelect) {
        console.error('找不到 HMAC 配置元素');
        return;
    }
    
    const algorithm = algorithmSelect.value;
    const encoding = encodingSelect.value;
    const transform = transformSelect.value;
    
    try {
        // 使用 CryptoJS 计算 HMAC
        let hmac;
        switch (algorithm) {
            case 'HmacMD5':
                hmac = CryptoJS.HmacMD5(message, key);
                break;
            case 'HmacSHA1':
                hmac = CryptoJS.HmacSHA1(message, key);
                break;
            case 'HmacSHA256':
                hmac = CryptoJS.HmacSHA256(message, key);
                break;
            case 'HmacSHA224':
                hmac = CryptoJS.HmacSHA224(message, key);
                break;
            case 'HmacSHA512':
                hmac = CryptoJS.HmacSHA512(message, key);
                break;
            case 'HmacSHA384':
                hmac = CryptoJS.HmacSHA384(message, key);
                break;
            case 'HmacSHA3':
                hmac = CryptoJS.HmacSHA3(message, key, { outputLength: 512 });
                break;
            default:
                // 默认使用 HMAC-SHA256
                hmac = CryptoJS.HmacSHA256(message, key);
        }
        
        // 格式化输出 - 根据编码格式转换
        let result;
        if (encoding === 'base64') {
            result = hmac.toString(CryptoJS.enc.Base64);
        } else {
            // 默认使用 Hex 编码
            result = hmac.toString(CryptoJS.enc.Hex);
        }
        
        // 大小写转换
        if (transform === 'upper') {
            result = result.toUpperCase();
        }
        
        // 显示结果
        displayResults([
            { label: algorithm, value: result }
        ]);
        
    } catch (error) {
        // 错误处理 - 显示友好的错误信息
        document.getElementById('results').innerHTML = 
            `<p style="text-align: center; color: #e74c3c;">计算失败: ${error.message}</p>`;
        console.error('HMAC 计算错误:', error);
    }
}
